package io.github.godfather1103.macro

import com.intellij.codeInsight.template.*
import com.intellij.util.containers.ContainerUtil

/**
 * <p>Title:        Godfather1103's Github</p>
 * <p>Copyright:    Copyright (c) 2023</p>
 * <p>Company:      https://github.com/godfather1103</p>
 *
 * @author  作者: Jack Chu E-mail: chuchuanbao@gmail.com
 * @date 创建时间：2023/8/24 15:38
 * @version 1.0
 * @since  1.0
 */
class MergeCollectionMacro : Macro() {

    override fun getName(): String = "mergeCollection"

    override fun getDefaultValue(): String = "[]"

    override fun getPresentableName(): String = "mergeCollection(Boolean=true, Collection1, Collection2, ...)"

    override fun calculateResult(params: Array<out Expression>, context: ExpressionContext?): Result? {
        if (params.isNotEmpty()) {
            val remove = params[0].calculateResult(context)?.let {
                when (it) {
                    is TextResult -> it.toString().toBoolean()
                    else -> true
                }
            } ?: true
            val p = params.mapNotNull {
                when (val r = it.calculateResult(context)) {
                    is ListResult -> {
                        val tmp = r.components
                        ContainerUtil.map(tmp) { i -> i.toString() }
                    }

                    else -> null
                }
            }.fold(mutableListOf<String>()) { acc, it ->
                acc.addAll(it)
                if (remove) acc.distinct().toMutableList() else acc
            }.map { TextResult(it) }
            return ListResult(p)
        }
        return null
    }
}